package com.solution.admin.product.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.solution.admin.product.dao.ProductCategoryDao;
import com.solution.admin.product.entity.ProductCategoryEntity;
import com.solution.admin.product.entity.ProductCategorySortEntity;
import com.solution.admin.product.service.ProductCategoryService;
import com.solution.admin.settings.dao.SortDao;
import com.solution.common.constants.PublicStatus.IS_DELETE;
import com.solution.common.constants.PublicStatus.STATUS;
import com.solution.common.dao.BaseDao;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.service.impl.BaseServiceImpl;
import com.solution.common.utils.string.StringUtil;

/**
 * 商品类别信息service实现层
 * @author xu_cc
 * @date 2017-08-31 23:52:27
 */
@Service
public class ProductCategoryServiceImpl extends BaseServiceImpl<ProductCategoryEntity> implements ProductCategoryService {

	/**
	 * 商品类别信息接口
	 */
	@Autowired
	private ProductCategoryDao productCategoryDao;
	@Autowired
	private SortDao sortDao;

	protected BaseDao<ProductCategoryEntity> getDao() {
		return this.productCategoryDao;
	}

	/**
	 * 保存商品类别信息
	 * @param ebProductCategoryEntity 商品类别信息实体
	 * @return Long 添加成功商品类别信息的ID
	 * @author xu_cc
	 * @date 2017-08-31 23:52:27
	 */
	@Transactional(rollbackFor=Exception.class)
	@Caching(evict = { @CacheEvict(value = "product", key = "'PRODUCT_CATEGORY'") })
	public long saveProductCategory(ProductCategoryEntity ebProductCategoryEntity) {
		//获取排序
		int sortNo = sortDao.getMaxSortNo("eb_product_category") + 1;
		ebProductCategoryEntity.setSortNo(sortNo);
		ebProductCategoryEntity.setIsDelete(IS_DELETE.NORMAL.getId());
		//保存
		long res = productCategoryDao.saveProductCategory(ebProductCategoryEntity);
		if (ebProductCategoryEntity.getId() != null) {
			//组装Path
			long parentCategoryId = ebProductCategoryEntity.getParentCategoryId();
			String parentPath = "0";
			String parentCategoryNamePath = "";
			if (parentCategoryId != 0) { 
				ProductCategoryEntity pc = productCategoryDao.getById(parentCategoryId);
				parentPath = pc.getPath();
				parentCategoryNamePath = pc.getCategoryNamePath();
			}
			String path = parentPath.concat("|").concat(String.valueOf(ebProductCategoryEntity.getId()));
			String categoryNamePath = "";
			if (StringUtil.isEmpty(parentCategoryNamePath)) {
				categoryNamePath = ebProductCategoryEntity.getCategoryName();
			} else {
				categoryNamePath = parentCategoryNamePath.concat("|").concat(ebProductCategoryEntity.getCategoryName());
			}
			
			ProductCategoryEntity updateParam = new ProductCategoryEntity();
			updateParam.setId(ebProductCategoryEntity.getId());
			updateParam.setPath(path);
			updateParam.setCategoryNamePath(categoryNamePath);
			productCategoryDao.updateProductCategory(updateParam);
		}
		// 重新加载分类排序
		doReloadCategorySort();
		return res;
	}

	/**
	 * 分页查询商品类别信息
	 * @param pageParam 分页参数
	 * @param paramMap 查询参数
	 * @return PageBean 分页参数和分页数据
	 * @author xu_cc
	 * @date 2017-08-31 23:52:27
	 */
	@Override
	public PageBean listProductCategoryPage(PageParam pageParam, Map<String, Object> paramMap) {
		return productCategoryDao.listProductCategoryPage(pageParam, paramMap);
	}
	
	/**
	 * 根据ID查询用户信息
	 * @param id 用户id
	 * @return ebProductCategoryEntity 用户对象
	 * @author xu_cc
	 * @date 2017-08-31 23:52:27
	 */
	public ProductCategoryEntity getProductCategoryById(Long id) {
		return productCategoryDao.getById(id.longValue());
	}

	/**
	 * 更新用户
	 * @param ebProductCategoryEntity 用户实体
	 * @return Long 更新是否成功，>1代表更新成功
	 * @author xu_cc
	 * @date 2017-08-31 23:52:27
	 */
	@Override
	@Caching(evict = { @CacheEvict(value = "product", key = "'PRODUCT_CATEGORY'") })
	public int updateProductCategory(ProductCategoryEntity ebProductCategoryEntity) {
		if (ebProductCategoryEntity.getParentCategoryId() != null) {
			ProductCategoryEntity productCategory = productCategoryDao.getById(ebProductCategoryEntity.getId());
			if (productCategory.getParentCategoryId() != ebProductCategoryEntity.getParentCategoryId()) {
				//组装Path
				long parentCategoryId = ebProductCategoryEntity.getParentCategoryId();
				String parentPath = "0";
				String parentCategoryNamePath = "";
				if (parentCategoryId != 0) { 
					ProductCategoryEntity pc = productCategoryDao.getById(parentCategoryId);
					parentPath = pc.getPath();
					parentCategoryNamePath = pc.getCategoryNamePath();
				}
				String path = parentPath.concat("|").concat(String.valueOf(ebProductCategoryEntity.getId()));
				String categoryNamePath = "";
				if (StringUtil.isEmpty(parentCategoryNamePath)) {
					categoryNamePath = ebProductCategoryEntity.getCategoryName();
				} else {
					categoryNamePath = parentCategoryNamePath.concat("|").concat(String.valueOf(ebProductCategoryEntity.getCategoryName()));
				}
				
				ebProductCategoryEntity.setPath(path);
				ebProductCategoryEntity.setCategoryNamePath(categoryNamePath);
			}
		}
		int rows = productCategoryDao.updateProductCategory(ebProductCategoryEntity);
		// 重新加载分类排序
		doReloadCategorySort();
		return rows;
	}
	
	
	/**
	 * 根据条件查询商品类别信息
	 * @param param
	 * @return 数据列表
	 * @author xu_cc
	 * @date 2017-08-31 23:52:27
	 */
	@Override
	public List<ProductCategoryEntity> listProductCategory(Map<String, Object> param){
		return  productCategoryDao.listProductCategory(param);
	}
	
	@Cacheable(value = "product", key = "'PRODUCT_CATEGORY'")
	public List<ProductCategoryEntity> listProductCategory(){
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("status", STATUS.ENABLED.getId());
		param.put("isDelete", IS_DELETE.NORMAL.getId());
		return  productCategoryDao.listProductCategory(param);
	}
	
	/**
	 * 删除商品类别信息
	 * @param 
	 * @return int 返回删除记录条数
	 * @author xu_cc
	 * @date 2017-08-31 23:52:27
	 */
	@Caching(evict = { @CacheEvict(value = "product", key = "'PRODUCT_CATEGORY'") })
	public int deleteProductCategoryById(long id){
		//return  productCategoryDao.deleteById(id);
		ProductCategoryEntity categoryParam = new ProductCategoryEntity();
		categoryParam.setId(id);
		categoryParam.setIsDelete(IS_DELETE.DELETED.getId());
		int rows = productCategoryDao.update(categoryParam);
		// 重新加载分类排序
		doReloadCategorySort();
		return  rows;
	}
	
	/**
	 * 根据关键字查询相关的商品类型
	 * @param param
	 * @return
	 * @author llp
	 */
	public List<ProductCategoryEntity> listProductCategoryBySearchKey(Map<String, Object> param){
		return productCategoryDao.listProductCategoryBySearchKey(param);
	}
	
	
	/**
	 * 查询PC端首页的商品类型
	 * @param param
	 * @return
	 * @author llp
	 */
	@Override
	public List<ProductCategoryEntity> listProductCategoryForIndex(Map<String, Object> param){
		return productCategoryDao.listProductCategoryForIndex(param);
	}
	
	/**
	 * 重新加载分类排序
	 * 
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2018年4月27日 下午5:54:45
	 */
	public void doReloadCategorySort() {
		// 首先获取当前所有有效的分类
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("status", 1);
		param.put("isDelete", 1);
		// 获取所有商品分类
		List<ProductCategoryEntity> categoryList = productCategoryDao.listProductCategory(param);
		if(null == categoryList) {
			return;
		}
		//记录每个分类的排序好
		Map<Long, Integer> categorySortMap = new HashMap<Long, Integer>();
		for (ProductCategoryEntity category : categoryList) {
			categorySortMap.put(category.getId(), category.getSortNo());
		}
		// 填充数据
		List<ProductCategorySortEntity> sortList = new ArrayList<ProductCategorySortEntity>();
		ProductCategorySortEntity sortEntity = null;
		String path = null;
		String[] idArr = null;
		for (ProductCategoryEntity category : categoryList) {
			sortEntity = new ProductCategorySortEntity();
			sortEntity.setId(category.getId());
			path = category.getPath().substring(2);
			idArr = path.split("\\|");
			if(idArr.length == 1) {
				Integer firstSortNo = categorySortMap.get(Long.parseLong(idArr[0]));
				sortEntity.setFirstSortNo(firstSortNo);
				sortEntity.setSecondSortNo(null);
				sortEntity.setThirdSortNo(null);
			} else if(idArr.length == 2) {
				Integer firstSortNo = categorySortMap.get(Long.parseLong(idArr[0]));
				Integer secondSortNo = categorySortMap.get(Long.parseLong(idArr[1]));
				sortEntity.setFirstSortNo(firstSortNo);
				sortEntity.setSecondSortNo(secondSortNo);
				sortEntity.setThirdSortNo(null);
			} else if(idArr.length == 3) {
				Integer firstSortNo = categorySortMap.get(Long.parseLong(idArr[0]));
				Integer secondSortNo = categorySortMap.get(Long.parseLong(idArr[1]));
				Integer thirdSortNo = categorySortMap.get(Long.parseLong(idArr[2]));
				sortEntity.setFirstSortNo(firstSortNo);
				sortEntity.setSecondSortNo(secondSortNo);
				sortEntity.setThirdSortNo(thirdSortNo);
			}
			sortList.add(sortEntity);
		}
		//do insert in db
		productCategoryDao.insertSortList(sortList);
	}

	/**
	 * 根据分类ID集合获取所有的分类
	 * @param categoryIds
	 * @return
	 * @author xkl
	 * @date 2018年6月12日 下午6:44:08
	 */
	@Override
	public Map<String, ProductCategoryEntity> listProductCategoryByIds(List<Long> categoryIds) {
		return productCategoryDao.listProductCategoryByIds(categoryIds);
	}
	
	/**
	 * 查询商品分类列表
	 * @param param
	 * @return
	 */
	@Override
	public List<ProductCategoryEntity> listProductCategoryForSelector(Map<String, Object> param){
		return  productCategoryDao.listProductCategoryForSelector(param);
	}
	
}
